#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <thread>

void recv_thread(int sock) {
    char buffer[1024];
    while (true) {
        ssize_t n = recv(sock, buffer, sizeof(buffer) - 1, 0);
        if (n <= 0) break;
        buffer[n] = '\0';
        std::cout << "Server: " << buffer << std::endl;
    }
}

int main()
{
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        std::cerr << "Socket creation failed\n";
        return 1;
    }

    sockaddr_in server_addr{};
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(18843);
    inet_pton(AF_INET, "8.138.10.61", &server_addr.sin_addr); // 服务器IP

    if (connect(sock, (sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        std::cerr << "Connect failed\n";
        close(sock);
        return 1;
    }

    // 启动接收线程
    std::thread t(recv_thread, sock);

    // 主线程负责发送
    std::string msg;
    while (true) {
        std::cout << "Input: ";
        std::getline(std::cin, msg);
        if (msg == "exit") break;
        send(sock, msg.c_str(), msg.size(), 0);
    }

    close(sock);
    t.join();
    return 0;
}